<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Constant\NewFlowEnum;
use App\Events\NewFlowOrderEvent;
use App\Events\RiskResultEvent;
use App\Facades\RiskPlatformRequestFacade;
use App\Models\UserApplyRiskLog;
use App\Models\UserAuthSpiderTransLog;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class QueryRiskJob implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    public $timeout = 30;

    protected $risk;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(UserApplyRiskLog $risk) {
        $this->risk = $risk;
        $this->onQueue(QueueKey::QUEUE_QUERY_RISK_RESULT);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() {
        $risk = $this->risk;
        try {
            $data['risk_id'] = $risk->risk_id;
            $ret             = RiskPlatformRequestFacade::queryRiskResult($data);
            //生产环境删除mock数据
//            $json = '{"code":"01","message":"操作成功","data":{"reason":"综合评分不足","resultCode":"AA","limit":"3000.00","resultDesc":"拒绝"},"sign":null}';
//            $ret = json_decode($json,true);
            if ($ret['code'] == '01') {
                if ($ret['data']['limit'] > 0) {
                    $limit = $ret['data']['limit'];
                } else {
                    $limit = 0;
                }
                $data      = [
                    'reason' => $ret['data']['reason'],
                    'limit'  => $limit,
                    'status' => UserApplyRiskLog::$STATUS[$ret['data']['resultCode']],
                ];
                $riskModel = UserApplyRiskLog::find($risk->id);
                $riskModel->update($data);
                $data['code'] = $ret['code'];
                \Log::debug('当前风控模型:' . json_encode($riskModel, JSON_UNESCAPED_UNICODE));
                event(new RiskResultEvent($riskModel));
                event(new NewFlowOrderEvent(NewFlowEnum::NewFlowRiskResult, false, $risk->loan_request_id, $data));
            }
        } catch (\Exception $e) {
            UserAuthSpiderTransLog::handleByStatus($risk->loan_request_id);
            \Log::debug('风控查询异常:' . $e->getMessage());
        }

    }
}
